﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Seagull.BarTender.Print;//需要安装bartender，或者把dll放进项目文件
using System.Drawing.Printing;
using System.Threading;
using System.Collections;
using System.Timers;
using System.Runtime.InteropServices;



namespace LabelPrint
{

    public partial class Form1 : Form
    {
        private bool isClosing = false; // 如果我们正在关闭，请设置为true。这有助于停止加载缩略图。
        private delegate void SetPos(int ipos);
        LabelFormatDocument btFormat;
       string DefaultPrinter1 ;
     
        public Form1()
        {
            InitializeComponent();

        }
        SQLServerDataBase sql = new SQLServerDataBase();
        static DateTime vipTime;
        private Engine engine = null; // The BarTender Print Engine
        private void Form1_Load(object sender, EventArgs e)
        {

            string[] arr = new string[] { "P20", "P50", "P60" };
            comboBox_packing.Items.AddRange(arr);



            string _connString = "server=192.168.2.99;database=admin;uid=sa;pwd=ljh6i22hc;";
            string getTime = "SELECT viptime FROM [dbo].[user] where id = 2";


           //读
            label7.Text = "使用时间:" + (vipTime - DateTime.Now).Days.ToString() + "天" + (vipTime - DateTime.Now).Hours.ToString() + "小时" + (vipTime - DateTime.Now).Minutes.ToString() + "分" + (vipTime - DateTime.Now).Seconds.ToString() + "秒";
            if (Convert.ToDateTime(sql.ExecuteSelectStr(getTime, _connString)) < DateTime.Now)
            {
                MessageBox.Show("打印服务组件试用到期，请重新联系IT获取使用权限");
                //    CanUse = false;
                this.Close();
                return;
            }
            try
            {
                engine = new Engine(true);
            }
            catch (PrintEngineException exception)
            {
             
                MessageBox.Show(this, exception.Message);
                this.Close(); 
                return;
            }
            // 得到打印机列表
            Printers printers = new Printers();
            foreach (Printer printer in printers)
            {
                cboPrinters.Items.Add(printer.PrinterName);
            }

            // cboPrinters.SelectedItem = btFormat.PrintSetup.PrinterName;
            cboPrinters.SelectedItem = DefaultPrinter();
            DefaultPrinter1 = DefaultPrinter();
            //  textBox3.Text = DefaultPrinter();
        }
        string type = "RC";
        string spec = "0805";
        string quantity = "5000";
        string R_value = "3R10";
        string Packaging = "P";
        string lot = "2316B00254";//10位
        string u_int = "F";
        string Power = "1/16W";
        int P_index = 0;
        string getLabel = "RC 0603 J N 100R 101 2319E00386";

        string aa = "";
        string bb = "";
        string cc = "";
        string dd = "";
        string ee = "";
        private string ff;

        private void oneFunction()
        {//RC0402J N 5K1 P50,1/16W,Q:50000,L:2416E00205,D:2416
           
            string[] contentArr = new string[20];
            string[] ItemCode_arr = new string[20];
            getLabel = textBox1.Text; // 获取扫出来的字
            contentArr = getLabel.Split(',');
            string item_code = contentArr[0];//获得品号字符串
            // getLabel = getLabel.Replace(" ", "");//去空格

            ItemCode_arr = item_code.Split(' ');

            u_int = ItemCode_arr[0].Substring(ItemCode_arr[0].Length-1,1);//精度

            int P_endIndex = getLabel.Length - 10;

            u_intRule();
  
            type =  ItemCode_arr[0].Substring(0,2);//RC  类别
          
            spec = ItemCode_arr[0].Substring(2,4);  //规格   
            R_value = ItemCode_arr[2];
            Packaging = ItemCode_arr[3];


            lot = contentArr[3].Substring(2,10);

           

 
            comboBox_packing.Text = Packaging;

            quantity = getQty(spec, Packaging);

            Power = getPower(type, spec);
            aa = R_value + "Ω±" + u_int;//zz + 精度
            bb = spec;//
            cc = Power;

            dd = quantity + "PCS";
            MessageBox.Show(dd);
            ee = lot;


            //  ff = arr[0] + arr[1] + arr[2] + " " + arr[3] + " " + arr[4] + " " + Packaging;
            ff = item_code;
        }

        /// <summary>
        /// 获取打印余数
        /// </summary>
        /// <param name="total">总数</param>
        /// <param name="box_count">每盘数量</param>
        /// <returns>打印数量</returns>
        private int twoFunction(int total, out int box_count)
        {//盒标
            int boxNum;
            string[] contentArr = new string[20];
            string[] ItemCode_arr = new string[20];
            getLabel = textBox1.Text; // 获取扫出来的字
            contentArr = getLabel.Split(',');
            string item_code = contentArr[0];//获得品号字符串
            // getLabel = getLabel.Replace(" ", "");//去空格

            ItemCode_arr = item_code.Split(' ');

            u_int = ItemCode_arr[0].Substring(ItemCode_arr[0].Length - 1, 1);//精度

            int P_endIndex = getLabel.Length - 10;

            u_intRule();

            type = ItemCode_arr[0].Substring(0, 2);//RC  类别

            spec = ItemCode_arr[0].Substring(2, 4);  //规格   
            R_value = ItemCode_arr[2];
            Packaging = ItemCode_arr[3];


            lot = contentArr[3].Substring(2, 10);




            comboBox_packing.Text = Packaging;

            quantity = getQty(spec, Packaging);

            Power = getPower(type, spec);
            aa = R_value + "Ω±" + u_int;//zz + 精度
            bb = spec;//
            cc = Power;
            dd = quantity + "PCS";
            ee = lot;
            ff = item_code;
            gg = u_int;


            if (Packaging == "P50")
            {//求余
                box_count = 250;
                boxNum = total % box_count;
                dd = 250000 + "";//250K
            }
            else if ((Packaging == "P20"))
            {
                box_count = 100;
                boxNum = total % box_count;
                dd = 100000 + ""; //100K   
            }
            else
            {
                box_count = 50;
                boxNum = total % box_count;
                dd = 50000 + ""; //100K   
            }       

            return boxNum;
        }
        private int thirdFunction(int total, out int box_count)//箱标
        {
            int boxNum;
            string[] contentArr = new string[20];
            string[] ItemCode_arr = new string[20];
            getLabel = textBox1.Text; // 获取扫出来的字
            contentArr = getLabel.Split(',');
            string item_code = contentArr[0];//获得品号字符串
            // getLabel = getLabel.Replace(" ", "");//去空格

            ItemCode_arr = item_code.Split(' ');

            u_int = ItemCode_arr[0].Substring(ItemCode_arr[0].Length - 1, 1);//精度

            int P_endIndex = getLabel.Length - 10;

            u_intRule();

            type = ItemCode_arr[0].Substring(0, 2);//RC  类别

            spec = ItemCode_arr[0].Substring(2, 4);  //规格   
            R_value = ItemCode_arr[2];
            Packaging = ItemCode_arr[3];


            lot = contentArr[3].Substring(2, 10);




            comboBox_packing.Text = Packaging;

            quantity = getQty(spec, Packaging);

            Power = getPower(type, spec);
            aa = R_value + "Ω±" + u_int;//zz + 精度
            bb = spec;//
            cc = Power;
            dd = quantity + "PCS";
            ee = lot;
            ff = item_code;
            gg = u_int;
            if (Packaging == "P50")
            {//求余
                box_count = 1250;
                boxNum = total % box_count;
                dd = 1250 + "";//1250K
            }
            else if (Packaging == "P20")
            {
                box_count = 500;
                boxNum = total % box_count;
                dd = 500 + ""; //500K   
            }
            else
            {
                box_count = 250;
                boxNum = total % box_count;
                dd = 250 + ""; //500K   
            }

         
            return boxNum;
        }

        private string getPack(string spec)
        {
            string packing = "";
            switch (spec)
            {
                case "0201":

                    packing = "P50";
                    break;
                case "0402":

                    packing = "P50";
                    break;
                case "0603":

                    packing = "P20";
                    break;
                case "0805":

                    packing = "P20";
                    break;
                case "1206":

                    packing = "P20";
                    break;
                default:
                    break;
            }
            return packing;
        }

        private void u_intRule()
        {
            if (u_int == "F")
            {
                u_int = "1%";
            }
            else
            {
                u_int = "5%";
            }
        }

        private string getPower(string type, string spec)
        {
            string power = "";
            switch (spec)
            {
                case "0201":
                    switch (type)
                    {
                        case "RC":
                            power = "1/20W";
                            break;
                        case "HP":
                            power = " ";
                            break;
                        case "HV":
                            power = " ";
                            break;
                        case "HS":
                            power = "1/20W";
                            break;
                        case "AS":
                            break;
                        case "LE":
                            break;
                    }
                    break;
                case "0402":
                    switch (type)
                    {
                        case "RC":
                            power = "1/16W";
                            break;
                        case "HP":
                            power = "1/10W";
                            break;
                        case "HV":
                            power = " ";
                            break;
                        case "HS":
                            power = "1/16W";
                            break;
                        case "AS":
                            break;
                        case "LE":
                            break;
                    }
                    break;
                case "0603":
                    switch (type)
                    {
                        case "RC":
                            power = "1/10W";
                            break;
                        case "HP":
                            power = "1/5W";
                            break;
                        case "HV":
                            power = "1/10W";
                            break;
                        case "HS":
                            power = "1/10W";
                            break;
                        case "AS":
                            power = "1/4W";
                            break;
                        case "LE":
                            power = "1/10W";
                            break;
                    }
                    break;
                case "0805":
                    switch (type)
                    {
                        case "RC":
                            power = "1/8W";
                            break;
                        case "HP":
                            power = "1/3W";
                            break;
                        case "HV":
                            power = "1/8W";
                            break;
                        case "HS":
                            power = "1/8W";
                            break;
                        case "AS":
                            power = "1/2W";
                            break;
                        case "LE":
                            power = "1/8W";
                            break;
                    }
                    break;
                case "1206":
                    switch (type)
                    {
                        case "RC":
                            power = "1/4W";
                            break;
                        case "HP":
                            power = "1/2W";
                            break;
                        case "HV":
                            power = "1/4W";
                            break;
                        case "HS":
                            power = "1/4W";
                            break;
                        case "AS":
                            power = "0.6W";
                            break;
                        case "LE":
                            power = "1/4W";
                            break;
                    }
                    break;
                case "1210":
                    switch (type)
                    {
                        case "RC":
                            power = "1/2W";
                            break;
                        case "HP":
                            power = "3/4W";
                            break;
                        case "HV":
                            power = "1/2W";
                            break;
                        case "HS":
                            power = "1/2W";
                            break;
                        case "AS":
                            power = "3/4W";
                            break;
                        case "LE":
                            power = "";
                            break;
                    }
                    break;
                case "2010":
                    switch (type)
                    {
                        case "RC":
                            power = "3/4W";
                            break;
                        case "HP":
                            power = "1W";
                            break;
                        case "HV":
                            power = "3/4W";
                            break;
                        case "HS":
                            power = "3/4W";
                            break;
                        case "AS":
                            power = "1.5W";
                            break;
                        case "LE":
                            power = "";
                            break;
                    }
                    break;
                case "2512":
                    switch (type)
                    {
                        case "RC":
                            power = "1W";
                            break;
                        case "HP":
                            power = "2W";
                            break;
                        case "HV":
                            power = "1W";
                            break;
                        case "HS":
                            power = "1W";
                            break;
                        case "AS":
                            power = "2W";
                            break;
                        case "LE":
                            power = "";
                            break;
                    }
                    break;
            }
            return power;
        }
        private string getQty(string spec, string packaging)
        {
           // 0402 每卷是50K，每盒是250K，0603 / 0805 / 1206每卷是20K，每盒是100K
            string qty = "";
            switch (spec)
            {
                case "0201":
                    if (packaging == "P")
                    {
                        qty = "15000";
                    }
                    else if (packaging == "P10")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P20")
                    {
                        qty = "20000";
                    }
                    else if (packaging == "P25")
                    {
                        qty = "25000";
                    }
                    else if(packaging == "P50")
                    {
                        qty = "50000";
                    }
                    else if (packaging == "P60")
                    {
                        qty = "60000";
                    }
                    break;

                case "0402":
                    if (packaging == "P")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P10")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P20")
                    {
                        qty = "20000";
                    }
                    else if (packaging == "P25")
                    {
                        qty = "25000";
                    }
                    else if (packaging == "P50")
                    {
                        qty = "50000";
                    }
                    else if (packaging == "P60")
                    {
                        qty = "60000";
                    }
                    break;

                case "0603":
                    if (packaging == "P")
                    {
                        qty = "5000";
                    }
                    else if (packaging == "P10")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P20")
                    {
                        qty = "20000";
                    }
                    else if (packaging == "P25")
                    {
                        qty = "25000";
                    }
                    else if (packaging == "P50")
                    {
                        qty = "50000";
                    }
                    else if (packaging == "P60")
                    {
                        qty = "60000";
                    }
                    break;

                case "0805":
                    if (packaging == "P")
                    {
                        qty = "5000";
                    }
                    else if (packaging == "P10")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P20")
                    {
                        qty = "20000";
                    }
                    else if (packaging == "P25")
                    {
                        qty = "25000";
                    }
                    else if (packaging == "P50")
                    {
                        qty = "50000";
                    }
                    else if (packaging == "P60")
                    {
                        qty = "60000";
                    }
                    break;

                case "1206":
                    if (packaging == "P")
                    {
                        qty = "5000";
                    }
                    else if (packaging == "P10")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P20")
                    {
                        qty = "20000";
                    }
                    else if (packaging == "P25")
                    {
                        qty = "25000";
                    }
                    else if (packaging == "P50")
                    {
                        qty = "50000";
                    }
                    else if (packaging == "P60")
                    {
                        qty = "60000";
                    }
                    break;

                case "1210":
                    if (packaging == "P")
                    {
                        qty = "5000";
                    }
                    else if (packaging == "P10")
                    {
                        qty = "10000";
                    }
                    else if (packaging == "P20")
                    {
                        qty = "20000";
                    }
                    else if (packaging == "P25")
                    {
                        qty = "25000";
                    }
                    else if (packaging == "P50")
                    {
                        qty = "50000";
                    }
                    else if (packaging == "P60")
                    {
                        qty = "60000";
                    }
                    break;

                

                case "2010":
                    if (packaging == "B")
                    {
                        qty = "4000";
                    }

                    break;

                case "2512":
                    if (packaging == "B")
                    {
                        qty = "4000";
                    }
                    break;
                default:
                    break;
            }
            return qty;
        }

        private static PrintDocument fPrintDocument = new PrintDocument();

        private string gg;
        private string hh;//地址
        private string ii;
        private int PrinterFlag = 0;

        public string jj;

        //获取本机默认打印机名称
        public static String DefaultPrinter()
        {
            return fPrintDocument.PrinterSettings.PrinterName;
        }


        private void print_pb()
        {
            try
            {


                yanzhen(1);
                oneFunction();

                printBtw("DownLabel.txt", textBox2.Text);
            }
            catch (Exception)
            {

                MessageBox.Show("输入的盘标格式不正确");
            }
        }
        private void print_hb()
        {
            //RC 0402 F N 0R11 P 5000 2323C00789 盒标
            //盒标，假设每盒500k,总量1020，打3盒，2盒500，1盒20
            if (!canPrint)
            {
                MessageBox.Show("不满足扫描5次，不得打印");
                return;
            }
            try
            {


                yanzhen(2);
                PrinterFlag = 2;
                int box_count;
                int total = Convert.ToInt32(Convert.ToDouble(textBox_total.Text.ToString()));
                int boxNum = twoFunction(total, out box_count);//获取打印余数



                if (boxNum > 0)
                {//有余数，多打一盒，数量为余数
                 //  150 < 50
                    if (total < box_count)//总数小于每盒数
                    {
                        printBtw("BoxLabel.txt", textBox5.Text, 1, boxNum, "盒标打印机");
                    }
                    else//一种是打整数，一种是打余数
                    {
                        if (printType == 0)
                        {
                            printBtw("BoxLabel.txt", textBox5.Text, 1, 0, "盒标打印机");
                        }
                        else
                        {
                            printBtw("BoxLabel.txt", textBox5.Text, 1, boxNum, "盒标打印机");
                        }


                        //    printBtw("BoxLabel.txt", textBox5.Text, (total - boxNum) / box_count, 0, "盒标打印机");
                        //printBtw("BoxLabel.txt", textBox5.Text, 1, boxNum, "盒标打印机");
                    }

                }
                else
                {//整数就打整数
                 // printBtw("BoxLabel.txt", textBox5.Text,total/ box_count, 0, "盒标打印机");
                    printBtw("BoxLabel.txt", textBox5.Text, 1, 0, "盒标打印机");
                }
            }
            catch (Exception)
            {

                MessageBox.Show("输入的盘标格式不正确");
            }

        }
        private void print_xb()
        {
            //RC 0402 F N 0R11 P 5000 2323C00789 箱标
            //箱标的数量标准是，根据订单总数进行拆解，0402每箱是1250K，0603 / 0805 / 1206每箱是500K

            if (!canPrint)
            {
                MessageBox.Show("不满足扫描5次，不得打印");
                return;
            }
            try
            {
                yanzhen(3);
                PrinterFlag = 3;
                //  Thread td = new Thread(() => printBtw("XiangLabel.txt", textBox6.Text));//开辟一个新的线程       
                //  td.Start();
                int box_count;
                int total = Convert.ToInt32(Convert.ToDouble(textBox_total.Text));//总数
                int moreBoxNum = thirdFunction(total, out box_count); //余数

                if (moreBoxNum > 0)
                {//有余数，多打一箱，数量为余数

                    if (total < box_count)//总数小于每箱数
                    {
                        printBtw("XiangLabel.txt", textBox6.Text, 1, moreBoxNum, "箱标打印机");
                    }
                    else
                    {
                        if (printType == 0)
                        {
                            printBtw("XiangLabel.txt", textBox6.Text, 1, 0, "箱标打印机");
                        }
                        else
                        {
                            printBtw("XiangLabel.txt", textBox6.Text, 1, moreBoxNum, "箱标打印机");//尾数打印
                        }
                        // printBtw("XiangLabel.txt", textBox6.Text, (total - moreBoxNum) / box_count, 0,"箱标打印机");

                    }

                }
                else
                {//整数就打箱数
                 // printBtw("XiangLabel.txt", textBox6.Text, total / box_count, 0, "箱标打印机");
                    printBtw("XiangLabel.txt", textBox6.Text, 1, 0, "箱标打印机");
                }
            }
            catch (Exception error)
            {

                MessageBox.Show(error.Message);
                return;
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {//打印与模板路径问题，默认路径是我开发电脑上的模板路径,RC 0402 F N 0R11 P 2323C00789|RC 0402 F 0R11 5000 2323C00789
        
            
        }

        /// <summary>
        /// 按需求打印
        /// </summary>
        /// <param name="FieldPath">模板名称</param>
        /// <param name="btw_path">模板路径</param>
        /// <param name="Copie">份数</param>
        /// <param name="remain">余数</param>
        void printBtw(string FieldPath, string btw_path,int Copie,int remain,string printName)
        { 
            lock (engine)
            {
                if (remain != 0)
                {
                    if (PrinterFlag==2)
                   {
                        dd = remain.ToString() + "000";
                   }
                else
                   {

                        dd = remain.ToString() + "";
                   
                   }
                }

                string path = AppDomain.CurrentDomain.BaseDirectory;

                //string serialNumber = "CUSTOMER_ITEM_NAME|CUSTOMER_ITEM_CODE|ITEM_DESCRIPTION|QTY\r\n" + CUSTOMER_ITEM_NAME + "|" + CUSTOMER_ITEM_CODE + "|" + ITEM_DESCRIPTION + "|" + QTY;
                string serialNumber = "resistance|size|wattage|quantity|lot_no|item_name|u_int|type|R_value|Packaging|addr|customer_name\r\n" + aa + "|" + bb + "|" + cc + "|" + dd + "|" + ee + "|" + ff + "|" + gg + "|" + type + "|" + R_value + "|" + Packaging + "|" + hh + "|" + ii;
                using (StreamWriter stream = new StreamWriter(path + "\\" + FieldPath))
                {
                    stream.Write(serialNumber);
                }
                //Lable 路径 

                string filePath = path + btw_path + ".btw";
                btFormat = engine.Documents.Open(filePath);
                //如何传参 命名具名数据源 赋予对应的 key<>value
                //          btFormat.SubStrings["ProductName"].Value = “test1”;
                //传入打印机名称
                btFormat.PrintSetup.PrinterName = printName;
                //打印张数
                btFormat.PrintSetup.IdenticalCopiesOfLabel = Copie;
                //     MessageBox.Show("开始打印");
                // btFormat.Print("UID Printing Job", 10000);//如果打不出来可能是软件安装不正确导致，重新安装可能会解决此问题
                Messages messages;
                string appName = "下标打印任务";
                Result result = btFormat.Print(appName, 10000, out messages);
                string messageString = "\n\nMessages:";

                //foreach (Seagull.BarTender.Print.Message message in messages)
                //{
                //    messageString += "\n\n" + message.Text;
                //}

                //if (result == Result.Failure)
                //{
                //    MessageBox.Show(this, "警告" + messageString, appName);
                //}

                //else
                //{
                //    MessageBox.Show(this, "文本已成功发送到打印机" + messageString, appName);
                //}

            }





        }

        void printBtw(string FieldPath, string btw_path)
        {

            lock (engine)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                //string serialNumber = "CUSTOMER_ITEM_NAME|CUSTOMER_ITEM_CODE|ITEM_DESCRIPTION|QTY\r\n" + CUSTOMER_ITEM_NAME + "|" + CUSTOMER_ITEM_CODE + "|" + ITEM_DESCRIPTION + "|" + dd;
                string serialNumber = "resistance|size|wattage|quantity|lot_no|item_name|u_int|addr|customer_name\r\n" + aa + "|" + bb + "|" + cc + "|" + dd + "|" + ee + "|" + ff + "|" + gg + "|" + hh + "|" + ii;


                using (StreamWriter stream = new StreamWriter(path + "\\" + FieldPath))
                {
                    stream.Write(serialNumber);
                }
                //Lable 路径 

                string filePath = path + btw_path + ".btw";
                 btFormat = engine.Documents.Open(filePath);
                //如何传参 命名具名数据源 赋予对应的 key<>value
                //          btFormat.SubStrings["ProductName"].Value = “test1”;
                //传入打印机名称
                btFormat.PrintSetup.PrinterName = cboPrinters.SelectedItem.ToString();
                //打印张数
                btFormat.PrintSetup.IdenticalCopiesOfLabel = Convert.ToInt32(textBox4.Text.ToString());
                //     MessageBox.Show("开始打印");
                // btFormat.Print("UID Printing Job", 10000);//如果打不出来可能是软件安装不正确导致，重新安装可能会解决此问题
                Messages messages;
                string appName = "下标打印任务";
                Result result = btFormat.Print(appName, 10000, out messages);
                string messageString = "\n\nMessages:";

                foreach (Seagull.BarTender.Print.Message message in messages)
                {
                    messageString += "\n\n" + message.Text;
                }

                if (result == Result.Failure)
                    MessageBox.Show(this, "Print Failed" + messageString, appName);
                else
                    MessageBox.Show(this, "文本已成功发送到打印机" + messageString, appName);
            }

            //btFormat.Close(SaveOptions.DoNotSaveChanges);
            //    engine.Stop();
            //}



        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //   printBtw("XiangLabel.txt", textBox6.Text);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (engine != null)
                engine.Stop(SaveOptions.DoNotSaveChanges);
        }

        private void button4_Click(object sender, EventArgs e)
        {
          
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //  isClosing = true;

            if (engine != null)
                engine.Stop(SaveOptions.DoNotSaveChanges);
        }
        DataSet ds1 = new DataSet();
        //DataTable ds2;
        int SelectColumnIndex;
        string SequenceNumber;
        string ITEM_DESCRIPTION;
        string CUSTOMER_ITEM_CODE;
        string total_num;//总数
        string CUSTOMER_ITEM_NAME;
        string ITEM_CODE;
        string BUSINESS_QTY;
        string LOT_CODE;
        string item_temp = "";
        bool canPrint=false;
        int hbs = 0;
        int xbs = 0;
        int scanCount = 0;
        int nowTotal = 0;
        int seq_no = 0;
        int seq_no_temp = 0;
        StringBuilder sqlStr = new StringBuilder();
        List<string> listXuhao = new List<string>();
      
        [DllImport("user32.dll")]
        //    static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
        Form f1 = new Form();
        DataGridView d1 = new DataGridView();
        private void button4_Click_1(object sender, EventArgs e)
        {//查询按钮      可以将原打印功能切分   打印整盒数用于5整除，打印余数用于余数相等时
           
           // listXuhao.AddRange(new string[]{});

          
            string[] contentArr = new string[20];
            string[] ItemCode_arr = new string[20];
            getLabel = textBox1.Text; // 获取扫出来的字
            contentArr = getLabel.Split(',');
            string ITEM_CODE = contentArr[0];//获得品号字符串

            


            count = 0;
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            
            f1.Size = new Size(800, 800);
         
            f1.Location = new Point(PointToScreen(button4.Location).X, PointToScreen(button4.Location).Y);
            f1.StartPosition = FormStartPosition.Manual; ;
            
            f1.Controls.Add(d1);

            f1.Load += F1_Load;
            d1.DataSource = null;
            //yanzhen(_connString, time);
            if (listXuhao.Count>0)
            {
                foreach (var item in listXuhao)
                {
                    sqlStr.AppendFormat(item + ",");
                }

            }
          
           // sqlStr.Append("\'\'") ;//拼接not in 字符

            try
            {
                sql.jiuwei_ExecuteNonDataSet("SELECT 销货通知单号,ITEM_CODE,客户名称,收货地址,品号,序号 FROM [dbo].[View_SALES_DELIVERY_JW] WHERE 销货通知单号 = '" + textBox_doc.Text + "' AND ITEM_CODE ='" + ITEM_CODE + "' AND 序号 NOT IN(" + sqlStr +"'')", out ds1);
            d1.DataSource = ds1.Tables[0];
            d1.AllowUserToAddRows = false;
            //  ds2 = ds1.Tables[0];
            d1.Size = new Size(800,800);
            d1.CellBeginEdit += D1_CellBeginEdit;            
            getLabel = textBox1.Text; // 获取扫出来的字
            contentArr = getLabel.Split(',');
            string item_code = contentArr[0];//获得品号字符串
         
            ItemCode_arr = item_code.Split(' ');
                u_int = ItemCode_arr[0].Substring(ItemCode_arr[0].Length - 1, 1);//精度
                int P_endIndex = getLabel.Length - 10;
                u_intRule();
                type = ItemCode_arr[0].Substring(0, 2);//RC  类别
                spec = ItemCode_arr[0].Substring(2, 4);  //规格   
                R_value = ItemCode_arr[2];
                Packaging = ItemCode_arr[3];
                lot = contentArr[3].Substring(2, 10);
                comboBox_packing.Text = Packaging;
                quantity = getQty(spec, Packaging);

                string sumQty = sql.ExecuteSelectStr("SELECT SUM([数量]) FROM [dbo].[View_SALES_DELIVERY_JW] WHERE 销货通知单号 = '" + textBox_doc.Text + "' AND ITEM_CODE ='" + ITEM_CODE + "'", 1);
                if(sumQty == "")
                {
                    MessageBox.Show("该单号已经出库完成，视图中无法搜索到");
                    return;

                }
            
                int total_num = Convert.ToInt32(Convert.ToDouble(sumQty));//等进到这一步，就说明该单号存在此品号

                textBox_total.Text = total_num.ToString();
                seq_no = Convert.ToInt32(ds1.Tables[0].Rows[0][5].ToString());
                if (scanCount == 0)//第一次扫描时，记录
                {
                    item_temp = ITEM_CODE;
                    nowTotal = total_num ;//第一次记录
                    seq_no_temp = seq_no;
                }





                //获取销货单号中的总数
           

                if (item_temp== ITEM_CODE&& nowTotal>0)//对比扫描的品号是否相同,序号是否相同
                {
                    scanCount++;
                    truePrintCount.Text = scanCount.ToString();
                    nowTotal -= Convert.ToInt32(quantity) / 1000;//每扫一次，就从总数中扣除
                 
                }
                else
                {
                    MessageBox.Show("扫描结束，或者该料盘不是5次扫描中的同一种！");
                    return;
                }
             
             

                hh = ds1.Tables[0].Rows[0][3].ToString();
                ii = ds1.Tables[0].Rows[0][2].ToString();
                string erp_item_code = ds1.Tables[0].Rows[0][1].ToString();
                if (scanCount % 5==0 && nowTotal != 0)
                {//满足5次后，才可以打印
                    hbs++;
                      canPrint = true;
                    print_hb();
                    printType = 0;//打整
                    if (scanCount % 25 == 0)//箱标
                    {
                        print_xb();
                    }
                    if (hbs % 5==0)
                    {
                        xbs++;
                    }                  
                  //  scanCount = 0;
                }
                else
                {//直接查询一下剩余数量是不是等于应该等于的余数
                    canPrint = true;
                    int box_count;
                    int total = Convert.ToInt32(Convert.ToDouble(textBox_total.Text));
                    int moreBoxNum = thirdFunction(total, out box_count); //余数
                   // int ys = Convert.ToInt32(Convert.ToDouble(total_num) % 50);//y余数
                    if (nowTotal == 0)//剩余数量=0时，说明此盘是最后一批料
                    {
                        printType = 1;//打余数
                        print_hb();//打盒标余数
                        Thread.Sleep(1000);

                        MessageBox.Show("开始打印箱数");

                        //auto press enter
                        keybd_event((byte)Keys.Enter, 0, 0, 0);                  
                        keybd_event((byte)Keys.Enter, 0, 2, 0);
                      

                       print_xb();//打箱标余数
                        bool isRepeat = listXuhao.Select(i => i.ToString()).Distinct().Count() != listXuhao.Count;
                        if (!isRepeat)
                        {
                            listXuhao.Add(seq_no.ToString());
                        } 
                       

                    }
                    else
                    {
                        canPrint = false;
                    }
                    
                  //  MessageBox.Show(hs+"");

                }

            


                hb_printCount_label.Text = hbs.ToString(); 
                xb_printCount_label.Text = xbs.ToString();
            }
            catch (Exception err)
            {
                MessageBox.Show("该盘料不在此销货单中，请确认！！"+err.Message);
                return;
            }


            d1.CellMouseDoubleClick -= D1_CellMouseDoubleClick;//先去除上次增加的代理事件
            d1.CellMouseDoubleClick += D1_CellMouseDoubleClick;//增加本次的代理事件
            d1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            Task.Factory.StartNew(() =>
            {
                //使用Invoke方法，让窗体在主线程中创建
                this.Invoke((MethodInvoker)delegate
                {
                    f1.Show();
                    textBox1.Clear();
                    textBox1.Focus();
                });
            });



        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
           
        }

        private static void autoCloseMsg()
        {

            MessageBox.Show("开始打印箱数");
          
        }

        private void F1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            System.Timers.Timer t = new System.Timers.Timer(2000);//实例化Timer类
            t.Elapsed += new System.Timers.ElapsedEventHandler(AutoClose);//到达时间的时候执行事件;
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true);
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;           
        }

        private void AutoClose(object sender, ElapsedEventArgs e)
        {
            f1.Hide();
        }

        private void yanzhen(int printType)
        {
            string printName1 = "";
            switch (printType)
            {
                case 1:
                    printName1 = "盘标";
                    break;
                case 2:
                    printName1 = "盒标";
                    break;
                case 3:
                    printName1 = "箱标";
                    break;
                default:
                    break;
            }
     

            string _connString = "server=192.168.2.99;database=admin;uid=sa;pwd=ljh6i22hc;";
            if (ds1.Tables.Count > 0)
            {
                ds1.Tables[0].Rows.Clear();
            }
            int sqlcount = Convert.ToInt32(sql.ExecuteSelectStr("SELECT COUNT(*) FROM print_log WHERE DOC_NO = '" + lot+ "'", _connString));
            if (sqlcount <= 0)
            {
                sql.ExecuteSelectStr("INSERT INTO print_log(DOC_NO,INSERT_INTO_TIME) VALUES ('" + lot + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')", _connString);
            }
            else
            {
                string print_id = sql.ExecuteSelectStr("SELECT ID FROM print_log WHERE DOC_NO = '" + lot + "'", _connString);
                sql.ExecuteSelectStr("INSERT INTO print_log_d(id,item_code,time,print_log_id,printType)VALUES ('" + Guid.NewGuid() +"','"+textBox1.Text+ "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + print_id +",N'"+ printName1 + "')", _connString);
                MessageBox.Show("请注意，此单号已被部分打印");
                keybd_event((byte)Keys.Enter, 0, 0, 0);
                keybd_event((byte)Keys.Enter, 0, 2, 0);
            }
        }

        int count = 0;
        private int printType;

        private void D1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {//选择完后赋值  

          
             ITEM_DESCRIPTION = ds1.Tables[0].Rows[e.RowIndex][1].ToString();
            CUSTOMER_ITEM_CODE = ds1.Tables[0].Rows[e.RowIndex][2].ToString();
            CUSTOMER_ITEM_NAME = ds1.Tables[0].Rows[e.RowIndex][3].ToString();
            ITEM_CODE = ds1.Tables[0].Rows[e.RowIndex][4].ToString();
            BUSINESS_QTY = ds1.Tables[0].Rows[e.RowIndex][5].ToString() ;
            textBox_total.Text = BUSINESS_QTY;
            //取最新生效日批次号 
             LOT_CODE = sql.ExecuteSelectStr("SELECT LOT_CODE FROM[dbo].[ITEM_LOT] A LEFT JOIN ITEM B ON A.ITEM_ID = B.ITEM_BUSINESS_ID WHERE B.ITEM_CODE = '"+ ITEM_CODE +"'  AND NOT INEFFECTIVE_DATE < '2021-07-27 08:55:07.0005969' ORDER BY EFFECTIVE_DATE DESC");



            ds1.Tables[0].Rows[e.RowIndex].Delete();
            ds1.AcceptChanges();//提交更改
            textBox1.Text = ITEM_CODE +" "+ LOT_CODE;
           count++;
            //  d1.Rows.RemoveAt(e.RowIndex);
        
            // f1.Close();

        }

        private void D1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button4.PerformClick();

            }
        }

        private void textBox_doc_TextChanged(object sender, EventArgs e)
        {//单号改变，则重置数量
            scanCount = 0;
            hbs = 0;
            xbs = 0;
        }
    }
}
